package com.leyou.trade.service.impl;

import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.respository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl  implements CartService {

    private final CartRepository repository;
    private final MongoTemplate mongoTemplate;
    public CartServiceImpl(CartRepository repository,MongoTemplate mongoTemplate){
        this.repository=repository;
        this.mongoTemplate=mongoTemplate;
    }
    @Override
    public void addCart(CartItem cartItem) {
     //获取用户信息
        Long userId = UserContext.getUser().getId();
        //查询购物车商品
        String id = createId(cartItem.getSkuId());
        //处理购物车商品
         cartItem = handleUpdateItem(userId, cartItem);
        //写入MongoDB
        repository.save(cartItem);
    }

    @Override
    public void updateNum(Long skuId, Integer num) {

        mongoTemplate.update(CartItem.class)
        //根据id匹配
        .matching(Query.query(Criteria.where("_id").is(createId(skuId))))
        //跟新num字段
        .apply(Update.update("num",num).currentDate("upadteTime"))
                .first();
    }

    @Override
    public List<CartItem> queryCartList() {
        //获取用户信息
        Long userId = UserContext.getUser().getId();

        //查询购物车
        List<CartItem> carts = repository.findByUserId(userId);
        return carts;
    }

    @Override
    public void deleteCart(Long skuId) {
        repository.deleteById(createId(skuId));
    }

    @Override
    public void addCartItemList(List<CartItem> itemList) {
       //获取用户id
        Long userId = UserContext.getUser().getId();
        //转换
       List<CartItem>list=itemList.stream()
               .map(item->
                       handleUpdateItem(userId,item)
                       ).collect(Collectors.toList());
       //新增或修改
        repository.saveAll(list);
    }

    private CartItem handleUpdateItem(Long userId,CartItem cartItem){
        //查询购物车商品
        Optional<CartItem> optional = repository.findById(createId(cartItem.getSkuId()));
        //判断购物车中是否存在与要添加的商品id一致的商品
        if (optional.isPresent()){
            //存在  记录新的商品数量
            Integer num = cartItem.getNum();
            //获取旧数据
            cartItem  = optional.get();
            //增加数量
            cartItem.setNum(num+cartItem.getNum());
        }
        //不存在 添加商品
        cartItem.setUserId(userId);
        cartItem.setUpdateTime(new Date());
        return cartItem;
    }
    private String createId(Long skuId){
        return String.format("u%ds%d",UserContext.getUser().getId(),skuId);
    }
}
